package indi.lqzhi.tcpserver.manager;

import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: LQZhi
 * @ClassName: BusManager
 * @Date: 2021-09-30 07-09
 * @Description: This is a BusManager Class.
 * @Version: V1.0
 */
public abstract class AbstractManager<K,V> implements Manager<K, V> {

    protected ConcurrentHashMap<K, V> concurrentHashMap;

    protected AbstractManager(){
        concurrentHashMap = new ConcurrentHashMap<>(32);
    }

    /**
     * 得到所有的客户端
     *
     * @return 所有的客户端
     */
    @Override
    public Collection<V> getAllClient() {
        return Collections.synchronizedCollection(concurrentHashMap.values());
    }

    /**
     * 清除所有的客户端
     */
    @Override
    public void clearAllClient() {
        concurrentHashMap.clear();//清空
    }

    /**
     * 得到客户端
     *
     * @param key 键
     * @return 客户端
     */
    @Override
    public Optional<V> getClient(K key) {
        return key == null ? Optional.empty() : Optional.ofNullable(concurrentHashMap.get(key));
    }

    /**
     * 返回所有存活的数量
     *
     * @return 存活的客户端数量
     */
    @Override
    public long getActiveClientCount() {
        return concurrentHashMap.size();
    }

    /**
     * 重置管理器，清空所有
     */
    @Override
    public void resetManager() {
        concurrentHashMap.clear();
    }

    /**
     * 注册客户端
     *
     * @param key   键
     * @param value 值
     * @return true 注册成功 false 注册失败
     */
    @Override
    public boolean register(K key, V value) {
        if (key == null || value == null){
            return false;
        }
        concurrentHashMap.put(key,value);
        return getClient(key).isPresent();
    }

    /**
     * 移除客户端
     *
     * @param key   键
     * @param value 值
     * @return true 移除成功 false 移除失败
     */
    @Override
    public boolean unregister(K key, V value) {
        if (key == null || value == null){
            return false;
        }
        concurrentHashMap.remove(key,value);
        return !getClient(key).isPresent();
    }
}
